module.exports = app => {
  const router = require('express').Router()
  const mongoose = require('mongoose')
  const Article = require('../../models/Article')
  const Category = require('../../models/Category')

  const data = require('./data/data')

  // 批量录入数据
  router.get('/news/init', async (req, res) => {
    // 找出一级分类
    const parent = await Category.findOne({
      name: '新闻分类'
    })
    // 找出一级分类下的所有子分类
    const cats = await Category.find().where({
      parent
    }).lean()
    const newsTitles = data.titleArr
    // 整理数据格式
    const newsList = newsTitles.map(title => {
      // 每次循环都将子分类随机排序
      const randomCat = cats.slice(0).sort((a, b) => Math.random() - 0.5)
      return {
        categories: randomCat.slice(0, 2),
        title
      }
    })
    // 先将数据库清空
    await Article.deleteMany({})
    await Article.insertMany(newsList)
    res.send(newsList)
  })

  router.get('/news/list', async (req, res) => {
    const parent = await Category.findOne({
      name: '新闻分类'
    })

    res.send(parent)
  })

  app.use('/web/api', router)
}